#!/usr/bin/env node
'use strict'

require('./util/prototype.js')
const fileUtil = require('./util/fileUtil')
const xlsx = require('node-xlsx')
const processData = (array, sheetname) => {
  let rowLength = array.length

  let colLength = array.map(item => item.length).max()

  //补齐列
  for (let i = 0; i < rowLength; i++) {
    if (array[i].length < colLength) {
      for (let j = array[i].length; j < colLength; j++) {
        array[i].push('')
      }
    }
  }

  //去除undefind
  for (let i = 0; i < rowLength; i++) {
    for (let j = 0; j < colLength; j++) {
      if (typeof array[i][j] == 'undefined') {
        array[i][j] = ''
      }
    }
  }

  let hasDel = false
  //删除空列
  let delCols = []
  for (let i = 0; i < colLength; i++) {
    if (array[0][i] == '') {
      let del = true
      for (let j = 0; j < rowLength; j++) {
        del = del && array[j][i] == ''
        hasDel = hasDel || del
      }
      if (del) {
        delCols.push(i)
      }
    }
  }

  if (hasDel) {
    array = array.map(row => {
      let newRow = []
      newRow = row.filter((value, index) => {
        return !delCols.contains(index)
      })
      return newRow
    })
  }

  //合并行到上面的行
  rowLength = array.length
  colLength = array.map(item => item.length).max()

  let newarray = []
  let k = 0
  for (let j = 0; j < rowLength; j++) {
    if (array[j][0] == '') {
      for (let i = 0; i < colLength; i++) {
        if (array[j][i] != '') {
          if (k > 0) {
            newarray[k - 1][i] = newarray[k - 1][i] + array[j][i]
          } else {
            console.log(sheetname)
          }
        }
      }
    } else {
      newarray.push(array[j])
      k++
    }
  }

  return newarray
}

module.exports = function(workFolder) {
  fileUtil
    .readDirPromise(
      workFolder,
      file => file.endsWith('.xls') && !file.startsWith('_')
    )
    .then(files => {
      files.map(file => {
        var filePath = `${workFolder}/${file}`
        var datas = xlsx.parse(filePath)
        datas = datas
          .filter(item => {
            return !item.name.startsWith('s')
          })
          .map(item => {
            item.data = processData(item.data, item.name)
            return item
          })
        fileUtil
          .writeExcelPromise(datas, `${workFolder}/_${file}`)
          .then(filePath => {
            console.log(`${filePath}已保存`)
          })
      })
    })
}
